<template>
  <div class="page-main"  v-title :data-title="dataTitle?dataTitle:'架构与合同跟进人'">
    <home-nav :userData="userinfo"></home-nav>
    <div class="banner"><span>架构与合同跟进人</span></div>
    <div class="container">
      <div class="header">
        <a-row type="flex" justify="space-between" align="middle">
          <a-col :xl="{ span: 14 }" :lg="{ span: 11 }">
            <a-button class="hte-btn add-btn" type="primary" icon="plus" @click="toAdd()">创建</a-button>
            <a-button class="hte-btn add-btn" @click="toEdit()">编辑</a-button>
            <a-button class="hte-btn del-btn" @click="toDel()">删除</a-button>
            <a-button class="hte-btn" @click="fetchList()">刷新</a-button>
            <a-button class="hte-btn" @click="asyncProjectPermission()">更新合同跟进人</a-button>
          </a-col>
          <a-col :xl="{ span: 9 }" :lg="{ span: 13 }" class="input-ground" style="justify-content: flex-end !important">
            <a-button class="hte-btn del-btn" @click="showSearchForm = true">高级搜索</a-button>
          </a-col>
        </a-row>
      </div>
      <div class="floatNav">
        <!-- <div class="budget-detail" @click="toMyTask">
          <span class="iconfont icon-reportReserve"></span>
          <a-badge :offset="[-11, -15]">
            <p>我的报工单</p>
          </a-badge>
        </div> -->
        <!-- <div class="budget-detail">
          <span class="iconfont icon-reportReserve"></span>
          <a-badge count="22" :offset="[-11, -15]">
            <p>验收付款单</p>
          </a-badge>
        </div> -->
      </div>
      <div class="content-list">
        <a-table
          :scroll="{ x: 1200 }"
          :columns="columns"
          :data-source="records"
          rowKey="id"
          bordered
          :pagination="false"
          @change="handleTableChange"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :customRow="customRow"
        >
          <span slot="actionRender" slot-scope="text, record">
            <span v-if="record.platForm == '海芯'" class="font-active" @click="toDel(record)"> 删除 </span>
            <span v-else class="font-active"> </span>
          </span>
        </a-table>
        <a-pagination
          show-size-changer
          :default-current="1"
          :total="pagination.total"
          @change="pageChange"
          @showSizeChange="onShowSizeChange"
          :show-total="(total) => `共 ${total} 条记录`"
        />
      </div>
    </div>
    <a-modal
      :visible="showSearchForm"
      width="70vw"
      :bodyStyle="{ padding: '10px' }"
      title="高级查询"
      @ok="handleToSearch"
      @cancel="showSearchForm = false"
    >
      <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item label="组织架构编码">
              <a-input allow-clear v-model="pagination.deptCode" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="组织架构名称">
              <a-input allow-clear v-model="pagination.deptName" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="组织架构全称">
              <a-input allow-clear v-model="pagination.deptNameAll" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item label="合同跟进人">
              <a-input allow-clear v-model="pagination.followUser" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="合同管理员">
              <a-input allow-clear v-model="pagination.managerUser" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
    <a-modal
      :visible="showEditForm"
      width="70vw"
      :bodyStyle="{ padding: '10px' }"
      title="编辑"
      @ok="handleToSave"
      @cancel="showEditForm = false"
    >
      <a-form-model ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="组织架构名称">
          <a-tree-select
            show-search
            v-model="editOrg.deptId"
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="orgTree"
            prop="deptName"
            @select="selectTree"
            @change="changeTree"
            allowClear
            tree-node-filter-prop="title"
            :replaceFields="{ children: 'children', title: 'deptname', key: 'randomStr', value: 'id' }"
          />
        </a-form-model-item>
        <a-form-model-item label="组织架构编码" prop="deptCode">
          <a-input disabled v-model="editOrg.deptCode" />
        </a-form-model-item>
        <a-form-model-item label="组织架构全称">
          <a-input disabled v-model="editOrg.deptNameAll" prop="deptNameAll" />
        </a-form-model-item>
        <a-form-model-item label="合同跟进人">
          <UserInputSelector
            :username.sync="editOrg.followUserId"
            :realname.sync="editOrg.followUser"
            multiple="multiple"
            placeholder="请选择"
          />
        </a-form-model-item>
        <a-form-model-item label="合同管理员">
          <UserInputSelector
            :username.sync="editOrg.managerUserId"
            :realname.sync="editOrg.managerUser"
            multiple="multiple"
            placeholder="请选择"
          />          
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
import { ColumnWidthMixin } from '@/views/materials/ColumnWidthMixin'
import { Modal } from 'ant-design-vue'
export default {
  mixins: [ColumnWidthMixin],
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
  },
  props: {},
  computed: {},
  data() {
    return {
      dataTitle:this.$route?this.$route.name:"",
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractTaskList',
      },
      labelCol: { span: 10 },
      wrapperCol: { span: 12 },
      columns: [
        {
          title: '架构编码',
          dataIndex: 'deptCode',
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '架构名称',
          dataIndex: 'deptName',
          width: '250px',
          align: 'left',
          ellipsis: true,
          customCell: () => {
            return {
              style: {
                width: '150px',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                cursor: 'pointer',
              },
            }
          },
          customRender: (text, record) => (
            <a-tooltip placement="topLeft" title={record.deptName}>
              {record.deptName}
            </a-tooltip>
          ),
        },
        {
          title: '架构全称',
          dataIndex: 'deptNameAll',
          width: '250px',
          align: 'left',
          ellipsis: true,
          customCell: () => {
            return {
              style: {
                width: '250px',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                cursor: 'pointer',
              },
            }
          },
          customRender: (text, record) => (
            <a-tooltip placement="topLeft" title={record.deptNameAll}>
              {record.deptNameAll}
            </a-tooltip>
          ),
        },
        {
          title: '合同跟进人',
          dataIndex: 'followUser',
          width: '120px',
          align: 'left',
          ellipsis: true,
        },
        {
          title: '合同管理员',
          dataIndex: 'managerUser',
          width: '200px',
          align: 'left',
          customCell: () => {
            return {
              style: {
                width: '200px',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                cursor: 'pointer',
              },
            }
          },
          customRender: (text, record) => (
            <a-tooltip placement="topLeft" title={record.managerUser}>
              {record.managerUser}
            </a-tooltip>
          ),
        },
        // {
        //   title: '操作',
        //   width: '100px',
        //   align: 'center',
        //   scopedSlots: { customRender: 'actionRender' },
        //   ellipsis: true,
        // },
      ],
      urls: {
        list: '/workReport/org/page',
        save: '/workReport/org/save',
        delete: '/workReport/org/delete',
        orgTree: '/masterData/depInfo/tree',
        asyncProjectPermission: '/workReport/org/asyncProjectPermission',
      },
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      pagination: {
        pageNo: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        total: 0,
      },
      orgTree: [],
      orgMap: [],
      editOrg: {},
      records: [],
      showSearchForm: false,
      showEditForm: false,
      selectedRowKeys: [],
      selectedRow: [],
    }
  },
  mounted() {
    this.fetchTree()
    this.fetchList()
  },
  methods: {
    handleSearch() {
      this.$set(this.pagination, 'pageNo', 1)
      this.fetchList()
    },
    onSelectChange(selectedRowKeys, selectedRow) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRow = selectedRow
    },
    customRow(record) {
      let that = this
      return {
        on: {
          dblclick: (event) => {
            let newKeyRows = []
            let exist = false
            this.selectedRowKeys.forEach((k) => {
              if (k != record.id) {
                newKeyRows.push(k)
              } else {
                exist = true
              }
            })
            if (!exist) {
              newKeyRows.push(record.id)
            }
            this.selectedRowKeys = newKeyRows

            let newRows = []
            this.selectedRow.forEach((k) => {
              if (k != record.id) {
                newRows.push(k)
              }
            })
            if (!exist) {
              newRows.push(record)
            }
            this.selectedRow = newRows
          },
          click(event) {},
        },
      }
    },
    fetchTree() {
      getAction(this.urls.orgTree, {}).then((res) => {
        if (res.success) {
          this.orgTree = this.setTreeRandomStr(res.result)
        }
      })
    },
    setTreeRandomStr(list) {
      list.forEach((l) => {
        this.$set(this.orgMap, l.id, l)
        l.randomStr = this.getRandomStr(20)
        if (l.children) {
          l.children = this.setTreeRandomStr(l.children)
        }
      })
      return list
    },
    selectTree(value) {
      if (this.orgMap[value]) {
        this.$set(this.editOrg, 'deptId', this.orgMap[value].id)
        this.$set(this.editOrg, 'deptCode', this.orgMap[value].deptcode)
        this.$set(this.editOrg, 'deptName', this.orgMap[value].deptname)
        this.$set(this.editOrg, 'deptNameAll', this.orgMap[value].deptnameall)
      } else {
        this.changeTree(null)
      }
    },
    changeTree(value) {
      if (!value) {
        this.$set(this.editOrg, 'deptId', '')
        this.$set(this.editOrg, 'deptCode', '')
        this.$set(this.editOrg, 'deptName', '')
        this.$set(this.editOrg, 'deptNameAll', '')
      }
    },
    fetchList() {
      let param = Object.assign({}, this.pagination)
      postAction(this.urls.list, param).then((res) => {
        if (res.success) {
          this.records = res.result.records
          this.$set(this.pagination, 'total', res.result.total)
          this.calcMaktxWidth(this.records, this.columns, [
            // 'deptCode',
            // 'deptName',
            'deptNameAll',
            // 'followUser',
            // 'managerUser',
          ])
        }
        this.showSearchForm = false
      })
    },
    /**
     * 表结构切换页码
     */
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination
      this.fetchList()
    },
    toDel() {
      if (!this.selectedRow || this.selectedRow.length <= 0) {
        return this.$messageWorkReport.warning('请至少选择一条记录操作')
      }
      let that = this
      Modal.confirm({
        title: '提醒',
        content: '是否确认删除',
        onOk() {
          postAction(that.urls.delete + '?id=' + that.selectedRowKeys.join(',')).then((res) => {
            if (res.success) {
              that.$messageWorkReport.success('删除成功')
              that.fetchList()
            } else {
              that.$messageWorkReport.error('删除失败')
            }
          })
        },
        onCancel() {},
      })
    },
    handleCancel() {
      this.$emit('hide')
    },
    pageChange(pageNo, pageSize) {
      this.$set(this.pagination, 'pageSize', pageSize)
      this.$set(this.pagination, 'pageNo', pageNo)
      this.fetchList()
    },
    onShowSizeChange(pageNo, pageSize) {
      this.$set(this.pagination, 'pageNo', pageNo)
      this.$set(this.pagination, 'pageSize', pageSize)
      this.fetchList()
    },
    handleToSearch() {
      this.$set(this.pagination, 'pageNo', 1)
      this.fetchList()
    },
    toAdd() {
      this.editOrg = {}
      this.showEditForm = true
    },
    toEdit() {
      if (!this.selectedRow || this.selectedRow.length != 1) {
        return this.$messageWorkReport.warning('请选择一条记录操作')
      }
      this.editOrg = Object.assign({}, this.selectedRow[0])
      this.showEditForm = true
    },
    handleToSave() {
      this.showEditForm = false
      postAction(this.urls.save, this.editOrg).then((res) => {
        if (res.success) {
          this.fetchList()
        }
      })
    },
    getRandomStr(len) {
      len = len || 32
      var $chars =
        'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      var maxPos = $chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    fillterFUN(searchVal, treeNode) {
      console.log(treeNode)
      return treeNode.data.props.name.includes(searchVal)
    },
    asyncProjectPermission() {
      if (!this.selectedRowKeys || this.selectedRowKeys.length <= 0) {
        return this.$messageWorkReport.warning('请至少选择一条记录更新')
      }
      postAction(this.urls.asyncProjectPermission, this.selectedRowKeys).then((res) => {
        if (res.success) {
          return this.$messageWorkReport.success('执行成功')
        } else {
          return this.$messageWorkReport.error('执行失败：' + res.message)
        }
      })
    },
  },
  watch: {},
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
.page-main {
  .banner {
    background-image: url(~@assets/contract-top.png);
  }
  .container {
    .content-list {
      margin-top: 15px;
    }
  }
  .font-active {
    cursor: pointer;
  }
}
.contentStyle-default {
  display: block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.contentStyle-red {
  display: block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: red;
}
.contentStyle-yellow {
  display: block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: burlywood;
}
</style>
